package com.demo.download.sample

import android.os.Bundle
import android.view.View
import androidx.appcompat.app.AppCompatActivity
import androidx.lifecycle.Observer
import androidx.lifecycle.ViewModelProvider
import androidx.recyclerview.widget.LinearLayoutManager
import androidx.recyclerview.widget.SimpleItemAnimator
import com.chad.library.adapter.base.BaseQuickAdapter
import com.chad.library.adapter.base.listener.OnItemChildClickListener
import com.demo.download.R
import com.demo.download.core.AppDownload
import com.demo.download.core.DownloadInfo
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity(), OnItemChildClickListener {

    private var appHomeAdapter: AppHomeAdapter? = null
    private var viewModel: MainViewModel? = null

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        initView()
        initData()
    }

    private fun initView() {
        recyclerView.layoutManager = LinearLayoutManager(this)
        val itemAnimator = recyclerView.itemAnimator
        if (itemAnimator is SimpleItemAnimator) {
            itemAnimator.supportsChangeAnimations = false
        }
        appHomeAdapter = AppHomeAdapter(data = null, lifecycleOwner = this)
        appHomeAdapter?.addChildClickViewIds(R.id.tb_status, R.id.tb_cancel)
        appHomeAdapter?.setOnItemChildClickListener(this)
        recyclerView.adapter = appHomeAdapter
    }

    private fun initData() {
        viewModel = ViewModelProvider(this)[MainViewModel::class.java]
        viewModel?.appListData?.observe(this, appListDataObserver)
        viewModel?.requestAppListData()
    }

    /**
     * App列表数据Observer
     */
    private val appListDataObserver: Observer<MutableList<App>> = Observer {
        appHomeAdapter?.setNewData(it)
    }

    override fun onItemChildClick(adapter: BaseQuickAdapter<*, *>, view: View, position: Int) {
        adapter as AppHomeAdapter
        val item = adapter.getItem(position)
        val downloadScope = AppDownload.request(url = item.downloadUrl, data = item)
        val downloadInfo = downloadScope?.downloadInfo()
        downloadInfo ?: return
        when (view.id) {
            R.id.tb_status -> {
                when (downloadInfo.status) {
                    DownloadInfo.ERROR, DownloadInfo.PAUSE, DownloadInfo.NONE -> downloadScope.start()
                    DownloadInfo.LOADING -> downloadScope.pause()
                }
            }
            R.id.tb_cancel -> {
                downloadScope.remove()
            }
        }
    }
}
